package com.yunshipei.manager.download;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DownloadManager;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


import com.yunshipei.core.net.EnterClient;
import com.yunshipei.enterplorer.R;
import com.yunshipei.manager.UpdateManager;
import com.yunshipei.utils.BaseUtil;
import com.yunshipei.utils.FileUtils;
import com.yunshipei.utils.ToastUtils;

import java.io.File;
import java.io.IOException;

import io.rong.app.activity.ToastUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

public class DownloadAppService extends Service {

    private static final String APP_DOWNLOAD_Path = Environment.getExternalStorageDirectory().getPath() + "/yunshipei/download/";
    private Dialog dialog;
    private ProgressBar progressBar;
    private TextView txtProgressBar;
    public DownloadAppService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    private NotificationManagerCompat mNotificationManager;

    @Override
    public void onCreate() {
        super.onCreate();
        mNotificationManager = NotificationManagerCompat.from(getApplicationContext());
    }

    private boolean isDownload = false;
    int layoutId = 0;// 布局ID
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("_d","onStartC");
        if (intent != null && !isDownload) {
            isDownload = true;
           startDownload(intent);










        }
        return super.onStartCommand(intent, flags, startId);
    }
    private void startDownload(Intent intent) {
        String versionName = intent.getStringExtra(UpdateManager.EXTRA_DOWNLOAD_APP_VERSION_NAME);
        String downloadUrl = intent.getStringExtra(UpdateManager.EXTRA_DOWNLOAD_URL);
        Log.e("downloadUrlsss",downloadUrl);
        final String appName = "中可OA_" + versionName + ".apk";
        final File srcFile = new File(APP_DOWNLOAD_Path, appName);
        final Request request = new Request.Builder().addHeader("Accept-Encoding", "gzip").url(downloadUrl).build();
        final MyProgressListener progressListener = new MyProgressListener(appName, mNotificationManager, 4999, this);
        Call call = ProgressHelper.addProgressResponseListener(EnterClient.getInstances().getManagerClient(), progressListener).newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                progressListener.onFailure("服务器错误");
                Log.e("ffffdd",e.getMessage()+"");
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                Log.e("ffff",response.code()+"");
                if (response.code() == 200) {
                    if (srcFile.exists() && srcFile.length() == response.body().contentLength()) {
                        progressListener.onProgress(srcFile.length(), srcFile.length(), true);

                        return;
                    }
                    if (srcFile.exists()) {
                        srcFile.delete();
                    }
                    FileUtils.writeToFile(APP_DOWNLOAD_Path, appName, response.body().byteStream());
                } else {
                    progressListener.onFailure("服务器错误");
                }
            }
        });

    }






    public class MyProgressListener extends UIProgressListener {

        private NotificationCompat.Builder mBuilder;

        private NotificationManagerCompat mNotificationManager;

        private String fileName;

        private int notificationID;

        private long mLastTime;

        private int currentProgress;

        private Context context;

        public MyProgressListener(String fileName, NotificationManagerCompat notificationManagerCompat, int notificationID, Context context) {
            this.fileName = fileName;
            this.mNotificationManager = notificationManagerCompat;
            this.notificationID = notificationID;
            this.mBuilder = new NotificationCompat.Builder(context);
            this.context = context;


        }

        @Override
        public void onUIStart(long currentBytes, long contentLength, boolean done) {
            mBuilder.setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(fileName)
                    .setContentText("开始下载")
                    .setProgress(100, 0, true)
                    .setTicker("开始下载" + fileName);
            updateNotification();

        }

        @Override
        public void onUIProgress(long currentBytes, long contentLength, boolean done) {
            if (mLastTime == 0) {
                mLastTime = System.currentTimeMillis();
            }
            int progress = currentBytes <= 0 ? 0 : (int) ((100 * currentBytes) / contentLength);
            long currentTime = System.currentTimeMillis();
            if (currentTime - mLastTime > 800) {
                currentProgress = progress;
                if (progress <= 0) {

                    mBuilder.setContentText("正在下载中...");
                    mBuilder.setProgress(100, progress, true);
//                    progressBar.setProgress(progress);
//                    txtProgressBar.setText("正在下载:" + progress + "%");
                } else {
//                    、rogressBar.setText("正在下载:" + progress + "%");
                    mBuilder.setProgress(100, progress, false);
                }
                updateNotification();
                mLastTime = currentTime;
            }
        }

        @Override
        public void onUIFinish(long currentBytes, long contentLength, boolean done) {
            mBuilder.setContentText("下载完成");
            mBuilder.setProgress(0, 0, false);
            mBuilder.setTicker(fileName + " 下载完成");
            updateNotification();
            if (dialog!=null) {
                dialog.dismiss();
            }
            BaseUtil.installAPK(context, new File(APP_DOWNLOAD_Path, fileName));
            mNotificationManager.cancel(notificationID);
            stopSelf();
        }

        @Override
        public void onUIFailure(String message) {
            mBuilder.setContentText("下载失败");
            mBuilder.setTicker(fileName + " 下载失败");
            mBuilder.setProgress(100, currentProgress, false);
            updateNotification();
            ToastUtils.showToast(message);
            if (dialog!=null) {
                dialog.dismiss();
            }
            stopSelf();
        }

        private void updateNotification() {
            mNotificationManager.notify(notificationID, mBuilder.build());
        }
    }

    @Override
    public void onDestroy() {
        isDownload = false;
        super.onDestroy();
    }




}